<script setup>
import ShortCut2 from "@/components/ShortCut2.vue";
import { useRouter } from "vue-router";
import { ref, onMounted } from "vue";
import { useShopcartStore } from "@/stores/shopcart";
import { storeToRefs } from "pinia";
import axios from "axios";
import { ElMessage } from 'element-plus';

const router = useRouter();
const shopcartStore = useShopcartStore();
const { checkedList, totalPrice, totalCount } = storeToRefs(shopcartStore);

// 执行确认订单操作，获取选中的商品
onMounted(() => {
  // 检查是否已登录
  if (!sessionStorage.getItem('token')) {
    ElMessage({
      message: '请先登录',
      type: 'warning'
    });
    router.push('/login');
    return;
  }
  
  shopcartStore.confirmOrder();
  
  // 如果没有选中商品，则提示并返回购物车页面
  if (checkedList.value.length === 0) {
    ElMessage({
      message: '请先选择要购买的商品',
      type: 'warning'
    });
    setTimeout(() => {
      router.push('/shopcart');
    }, 1500);
  }
});

// 提交订单
let recipient = ref("");
let phone = ref("");
let address = ref("");
let books = ref([]);

// 准备订单商品信息
const prepareOrderItems = () => {
  books.value = checkedList.value.map(item => {
    return {
      "cart_id": item.cart_id,
      "b_id": item.b_id,
      "num": item.num
    }
  });
};

// 验证表单数据
const validateForm = () => {
  if (!recipient.value.trim()) {
    ElMessage.warning('请输入收货人姓名');
    return false;
  }
  if (!phone.value.trim()) {
    ElMessage.warning('请输入联系电话');
    return false;
  }
  if (!address.value.trim()) {
    ElMessage.warning('请输入详细地址');
    return false;
  }
  return true;
};

// 提交订单
const addOrder = async () => {
  if (!validateForm()) return;
  
  // 检查是否已登录
  if (!sessionStorage.getItem('token')) {
    ElMessage({
      message: '请先登录',
      type: 'warning'
    });
    router.push('/login');
    return;
  }
  
  prepareOrderItems();
  
  if (books.value.length === 0) {
    ElMessage.warning('请选择要购买的商品');
    return;
  }
  
  // 准备订单数据
  const orderData = {
    "recipient": recipient.value,
    "phone": phone.value,
    "address": address.value,
    "totalprice": totalPrice.value,
    "books": books.value
  };
  
  try {
    const res = await axios.post('/api/addOrder', orderData);
    if (res.data.code === 200) {
      ElMessage({
        message: res.data.message || '订单提交成功',
        type: 'success'
      });
      router.push('/order');
    } else {
      ElMessage({
        message: res.data.message || '订单提交失败',
        type: 'error'
      });
    }
  } catch (err) {
    console.error('提交订单错误:', err);
    
    // 检查是否是401未授权错误
    if (err.response && err.response.status === 401) {
      ElMessage({
        message: '登录已过期，请重新登录',
        type: 'error'
      });
      router.push('/login');
      return;
    }
    
    ElMessage({
      message: '订单提交失败: ' + ((err.response && err.response.data && err.response.data.message) || err.message || '未知错误'),
      type: 'error'
    });
  }
};
</script>

<template>
  <div>
    <ShortCut2></ShortCut2>
    <div id="app">
      <div class="shoppingProcedure">
        <span>我的购物车</span>
        <span class="current">填写核对订单信息</span>
        <span>成功提交订单</span>
      </div>
      <div class="shoppingTip">
        <strong>填写核对订单信息</strong>
      </div>
      
      <!-- 订单商品列表 -->
      <div class="order-items">
        <h3>订单商品信息</h3>
        <table class="order-table">
          <thead>
            <tr>
              <th width="15%">商品图片</th>
              <th width="40%">商品名称</th>
              <th width="15%">单价</th>
              <th width="15%">数量</th>
              <th width="15%">小计</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in checkedList" :key="item.cart_id">
              <td class="product-img">
                <img :src="item.img" :alt="item.bookname" />
              </td>
              <td class="product-name">{{ item.bookname }}</td>
              <td class="product-price">¥{{ item.price }}</td>
              <td class="product-quantity">{{ item.num }}</td>
              <td class="product-subtotal">¥{{ (item.price * item.num).toFixed(2) }}</td>
            </tr>
          </tbody>
          <tfoot>
            <tr>
              <td colspan="5" class="order-total">
                <div class="total-info">
                  <span>共 <strong>{{ totalCount }}</strong> 件商品</span>
                  <span>合计: <strong class="price-total">¥{{ totalPrice.toFixed(2) }}</strong></span>
                </div>
              </td>
            </tr>
          </tfoot>
        </table>
      </div>
      
      <div class="orderInfo">
        <div class="consigneeBox">
          <!--新用户添加地址-->
          <div class="newUserAddr addr">
            <div class="stepTit clearfix"><strong>收货人信息</strong></div>
            <div class="addressForm">
              <form @submit.prevent="addOrder">
                <div class="listInfo clearfix">
                  <label class="label_w80" for="recipient"
                    ><strong>*</strong>收&nbsp;&nbsp;货&nbsp;&nbsp;人：</label
                  ><input
                    class="inputW198"
                    type="text"
                    id="recipient"
                    required
                    v-model="recipient"
                  /><span class="hide error-msg" id="name_div_error"></span>
                </div>
                <div class="listInfo consigneeAddr_box clearfix" id="area_div">
                  <label class="label_w80"><strong>*</strong>收货地区：</label
                  ><select name="country">
                    <option selected="selected" value="中国">中国</option>
                    <option value="其他国家">其他国家</option></select
                  ><select name="provice">
                    <option value="请选择-0" selected="selected">请选择</option>
                    <option value="北京-110000">北京</option>
                    <option value="天津-120000">天津</option>
                    <option value="河北-130000">河北</option>
                    <option value="山西-140000">山西</option>
                    <option value="内蒙古-150000">内蒙古</option>
                    <option value="辽宁-210000">辽宁</option>
                    <option value="吉林-220000">吉林</option>
                    <option value="黑龙江-230000">黑龙江</option>
                    <option value="上海-310000">上海</option>
                    <option value="江苏-320000">江苏</option>
                    <option value="浙江-330000">浙江</option>
                    <option value="安徽-340000">安徽</option>
                    <option value="福建-350000">福建</option>
                    <option value="江西-360000">江西</option>
                    <option value="山东-370000">山东</option>
                    <option value="河南-410000">河南</option>
                    <option value="湖北-420000">湖北</option>
                    <option value="湖南-430000">湖南</option>
                    <option value="广东-440000">广东</option>
                    <option value="广西-450000">广西</option>
                    <option value="海南-460000">海南</option>
                    <option value="重庆-500000">重庆</option>
                    <option value="四川-510000">四川</option>
                    <option value="贵州-520000">贵州</option>
                    <option value="云南-530000">云南</option>
                    <option value="西藏-540000">西藏</option>
                    <option value="陕西-610000">陕西</option>
                    <option value="甘肃-620000">甘肃</option>
                    <option value="青海-630000">青海</option>
                    <option value="宁夏-640000">宁夏</option>
                    <option value="新疆-650000">新疆</option>
                    <option value="台湾-710000">台湾</option>
                    <option value="香港-810000">香港</option>
                    <option value="澳门-820000">澳门</option></select
                  ><span class="error-msg hide message"></span>
                </div>
                <div class="listInfo clearfix">
                  <label class="label_w80" for="address"
                    ><strong>*</strong>详细地址：</label
                  ><input
                    class="inputW438"
                    type="text"
                    id="address"
                    required
                    v-model="address"
                  /><span class="error-msg hide" id="address_div_error"></span>
                </div>
                <div class="listInfo consigneePhone_box clearfix">
                  <label class="label_w80" for="phone"
                    ><strong>*</strong
                    >手&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;机：</label
                  ><input
                    class="inputW198"
                    type="text"
                    id="phone"
                    required
                    v-model="phone"
                  /><span class="error-msg hide" id="call_div_error"></span>
                </div>
                <div class="listInfo consigneeSave_box">
                  <button
                    type="submit"
                    :disabled="checkedList.length <= 0"
                    class="submit-btn"
                  >
                    提交订单
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
#app {
  width: 1000px;
  margin: 0 auto;
}

/* 订单商品表格样式 */
.order-items {
  margin: 20px 0;
  border: 1px solid #e4e4e4;
  border-radius: 4px;
  padding: 15px;
  background-color: #fff;
}

.order-items h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e4e4;
}

.order-table {
  width: 100%;
  border-collapse: collapse;
}

.order-table th {
  background-color: #f5f5f5;
  padding: 10px;
  text-align: center;
  font-weight: normal;
  color: #666;
}

.order-table td {
  padding: 15px 10px;
  text-align: center;
  border-bottom: 1px solid #e4e4e4;
}

.order-table .product-img img {
  width: 80px;
  height: auto;
  object-fit: cover;
  border: 1px solid #e4e4e4;
}

.order-table .product-name {
  text-align: left;
  color: #333;
}

.order-table .product-price,
.order-table .product-subtotal {
  color: #f80000;
  font-weight: bold;
}

.order-table .order-total {
  padding: 15px;
  text-align: right;
  border-bottom: none;
}

.order-table .total-info {
  display: flex;
  justify-content: flex-end;
  gap: 20px;
}

.order-table .price-total {
  color: #f80000;
  font-size: 18px;
}

/* //////////////////// */
.shoppingProcedure {
  width: 617px;
  height: 36px;
  line-height: 36px;
  overflow: hidden;
  background: url("/src/assets/orderInfoProced.png") no-repeat left center;
  margin: 28px 0px;
}
.shoppingProcedure span {
  float: left;
  width: 204px;
  height: 36px;
  color: #666;
  font-size: 14px;
  text-align: center;
  padding: 0px 0px 0px 20px;
}
.shoppingProcedure span.current {
  color: #fff;
}
.shoppingTip {
  height: 26px;
  overflow: hidden;
}
.shoppingTip strong {
  height: 26px;
  line-height: 26px;
  float: left;
  font-size: 20px;
  color: #414141;
  padding-right: 16px;
  background: url(https://www.bookschina.com/shopcar/images/tipbg.jpg) no-repeat
    right center;
}
.orderInfo {
  border: 1px solid #dbdbdb;
  margin-top: 23px;
}
.stepTit {
  background: #e9e9e9;
  line-height: 30px;
  margin: 26px 19px 0px;
}
.clearfix {
  zoom: 1;
  display: block;
}
.stepTit strong {
  color: #333;
  font-size: 14px;
  font-weight: bold;
  padding: 0px 0px 0px 20px;
  float: left;
}
.orderInfo .newUserAddr .addressForm {
  padding: 0px 19px;
}
.orderInfo .newUserAddr .addressForm .listInfo {
  margin: 20px 0px 0px;
}
.addressForm label.label_w80 {
  float: left;
  width: 80px;
  text-align: left;
  color: #333;
  line-height: 28px;
  font-size: 12px;
}
.orderInfo .newUserAddr .addressForm label {
  float: left;
  line-height: 28px;
}
.addressForm label strong {
  color: #f80000;
  font-weight: bold;
  margin: 0px 7px 0px 0px;
}
.orderInfo .newUserAddr .addressForm input {
  float: left;
  height: 26px;
  line-height: 26px;
  border: 1px solid #d4d4d4;
  background: #fff;
  vertical-align: middle;
  font-size: 12px;
  text-indent: 1em;
  color: #333;
}
.addressForm input.inputW198 {
  width: 198px;
}
.addressForm span.hide {
  overflow: hidden;
  margin: 0px 0px 0px 15px;
  color: #f80000;
}
.orderInfo .newUserAddr .addressForm select {
  float: left;
  height: 26px;
  margin: 0px 10px 0px 0px;
  border: 1px solid #d4d4d4;
  padding: 0px 5px;
}
.addressForm input.inputW438 {
  width: 428px;
}
.orderInfo .newUserAddr .addressForm .consigneeSave_box button {
  cursor: pointer;
  width: 120px;
  height: 36px;
  color: #fff;
  background: #f80000;
  font-weight: bold;
  border-radius: 5px;
  border: none;
}

.submit-btn {
  cursor: pointer;
  padding: 10px 25px;
  color: #fff;
  background: #f80000;
  font-weight: bold;
  border-radius: 5px;
  border: none;
  font-size: 16px;
}

.submit-btn:hover {
  background: #e60000;
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>
